use crate::{ApiError, ApiResult, ToError};
use data_encoding::BASE64;

/// base64 编码
pub fn encode<D: AsRef<[u8]>>(data: D) -> String {
    BASE64.encode(data.as_ref())
}

/// base64 解码
pub fn decode_vec<D: AsRef<[u8]>>(data: D) -> ApiResult<Vec<u8>> {
    BASE64
        .decode(data.as_ref())
        .to_err(|| ApiError::Biz("base64解码错误".into()))
}

/// base64解码
pub fn decode<D: AsRef<[u8]>>(data: D) -> ApiResult<String> {
    let vec = BASE64
        .decode(data.as_ref())
        .to_err(|| ApiError::Biz("base64解码错误".into()))?;
    String::from_utf8(vec).to_err(|| ApiError::Biz("base64解码错误".into()))
}
